package com.gotloop.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.gotloop.jdo.UserProfile;

/**
 * User DAO Implementation.
 * @author jibhaine
 *
 */
@Repository
public class UserDAOImpl extends AbstractDAOImpl<UserProfile, String> implements UserDAO {

	/**
	 * Logger for UserDAOImpl.
	 */
	private static final Logger LOG = LoggerFactory.getLogger(UserDAOImpl.class);

	@SuppressWarnings("unchecked")
	@Override 
	public UserProfile getUserByName(String pName) {
		LOG.debug("getUserByName({})", pName);
		UserProfile userProfile = null;
		PersistenceManager pManager = getPersistenceManager();
		Query query = pManager.newQuery(getEntityClass(), "name == pName");
		query.declareParameters("String pName");
		try {
			List<UserProfile> userList = (List<UserProfile>) query.execute(pName);
			//userList = (List<User>) pManager.detachCopyAll(userList);
			if (!userList.isEmpty()) {
				userProfile = userList.get(0);
			}
		} catch (Exception e) {
			LOG.error("Exception " + e.getLocalizedMessage());
		} finally {
			pManager.close();
		}
		return userProfile;
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserProfile getUserByEmail(String pEmail) {
		LOG.debug("getUserByEmail({})", pEmail);
		UserProfile userProfile = null;
		PersistenceManager pManager = getPersistenceManager();
		Query query = pManager.newQuery(getEntityClass(), "email == pEmail");
		try {
			query.declareParameters("String pEmail");
			List<UserProfile> userList = (List<UserProfile>) query.execute(pEmail);
			userList = (List<UserProfile>) pManager.detachCopyAll(userList);
			if (!userList.isEmpty()) {
				userProfile = userList.get(0);
			} else {
				userProfile = null;
			}
		} catch (Exception e) {
			LOG.error("Exception " + e.getLocalizedMessage());
		} finally {
			pManager.close();
		}
		return userProfile;
	}

}
